/**
 * $version:  0.1 
 * $Date: 2012-03-19 
 *
 * Copyright (C) 2010-2011 Jawa Software. All rights reserved.
 *
 */

package org.jawa.core.container;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 动态注册和未登记插件类的过滤逻类
 *
 * @author Matt Tucker
 */
public class PluginFilter implements Filter {

    private static List<SimpleFilter> pluginFilters = new CopyOnWriteArrayList<SimpleFilter>();

    /**
     * 每次请求时将 filter添加到过滤器列表中，该方法会在插件启动时调用
     *
     * @param filter SimpleFilter实例.
     */
    public static void addPluginFilter(SimpleFilter filter) {
        pluginFilters.add(filter);
    }

    /**
     * 每次请求时将过滤器从列表中删除
     * 该方法在插件关闭时调用.
     *
     * @param filter SimpleFilter实例.
     */
    public static void removePluginFilter(SimpleFilter filter) {
        pluginFilters.remove(filter);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException
    {
        boolean continueChain = true;
        // 处理每个插件过滤器。
        for (SimpleFilter filter : pluginFilters) {
            if (!filter.doFilter(servletRequest, servletResponse)) {
                continueChain = false;
                break;
            }
        }
        if (continueChain) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    public void destroy() {
    	//JawaServer的实例关闭时调用destroy方法,清除插件过滤器列表。
        pluginFilters.clear();
    }

    /**
     * servlet过滤器的一个简化版本. 
     */
    public interface SimpleFilter {

        /**
         * 该过滤器将适用于所有在管理控制台中的JSP页面的请求和在各自的插件不只是请求
         */
        public boolean doFilter(ServletRequest request, ServletResponse response)
                throws IOException, ServletException;

    }
}